import base64


class Base64Util(object):
    def decode_base64_file(self, code, path=None):
        """
        下载base64格式资源并保存至本地
        :param code: 资源base64编码
        :param path: 保存地址
        :return: path
        """
        b64 = code.split(',')
        b64_file = b64[0].split(';')
        suffix = b64_file[0].split('/')[1]
        # re.findall(r'data:.*?/(.*?)', b64_file[0])
        if suffix.__len__() == 0:
            # TODO 异常
            pass
        if suffix == "vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            suffix = "xlsx"
        if suffix == "vnd.ms-excel":
            suffix = "xls"
        if path is None:
            path = "%s.%s" % ("none", suffix)
        self.save_base64_file(b64[1], path)
        return path

    def save_base64_file(self, code, path):
        """
        存储base64文件
        :param code:
        :param path:
        :return:
        """
        file_code = base64.b64decode(code)
        with open(path, 'wb') as f:
            f.write(file_code)
            f.close()


if __name__ == '__main__':
    a = Base64Util()
    # code = """"""
    code = """"""
    path = "test.png"
    a.decode_base64_file(code, path)